import time

import facade
from xjlibrary.MRabbitMQ.useMQ.sendmq import SendMQUse
from xjlibrary.configread import MyConfigParser
from xjlibrary.myredis.myredisclient import getDataFromRedis

from xjlibrary.our_file_dir.base_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -3)
sPath = BaseDir.get_new_path(TopPath, "download", "jstor", "download", "article")

logger = facade.get_streamlogger()
mysqlutils = facade.MysqlUtiles(BaseDir.get_new_path(BaseDir.get_upper_dir(curPath, -1),"db.ini"), "db", logger=logger)

# # 数据库链接
# def MajorDbConnect():
#     return MySqlDbConnect(BaseDir.get_upper_dir(curPath, -1), "db.ini")


def readDBProxy():
    return getDataFromRedis(BaseDir.get_upper_dir(curPath, -1), 'db.ini')


# 刷新任务池（从数据库获取任务）
def UpdateTaskPool():
    sql = "SELECT url FROM article WHERE stat=0 AND failcount<3 limit 10000;"
    rows = mysqlutils.SelectFromDB(sql)
    # conn = MajorDbConnect()
    # rows = SelctSqlFromDB(sql, conn)
    # listurl = []
    # for row in rows:
    #     listurl.append(row[0])
    # if len(listurl) == 1:
    #     listurl.append("test")
    # sql = "update article set stat=-1 where url in {}".format(tuple(listurl))
    #
    return rows


class Send(SendMQUse):
    def __init__(self, cofig, queuetest):
        super(Send, self).__init__(cofig, queuetest)

    def UpdateProxyPool(self):
        rows = readDBProxy()
        self.ProxyPool = list(rows)
        print('Update TaskPool: %d' % len(self.TaskPool))
        print('current time:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    def UpdateTaskPool(self):
        """
        重写更新任务
        :return:
        """
        print('Update ProxyPool: %d' % len(self.ProxyPool))
        print('current time:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        rows = UpdateTaskPool()
        for row in rows:
            dic = {
                'url': row[0].strip()
            }
            self.TaskPool.append(dic)


if __name__ == "__main__":
    config = BaseDir.get_new_path(BaseDir.get_upper_dir(curPath, -1), "db.ini")
    GolobalConfig = MyConfigParser().get_conf_dict_file(config)
    queueCenter2Node = GolobalConfig['get_article']['MQQueueCenter2Node']
    send = Send(config, queueCenter2Node)
    send.UpdateProxyPool()
    send.set_queue_declare(passive=True)
    send.run()
